<template>
  <Split
    direction="horizontal"
    :style="{ height: '100%' }"
    v-model:size="splitSize"
    :resize-trigger-size="5"
    :min="0"
    :max="0.23"
  >
    <template #1>
      <OrgTree
        ref="orgTreeRef"
        @hide="handleHideOrgTree"
        @set="handleSetOrg"
        @reload="reloadTable"
        @loaded="handleOrgTreeLoaded"
      />
    </template>

    <template #2>
      <n-card :bordered="false" class="proCard" :style="{ width: '100%', height: '100%' }">
        <BasicForm @register="registerForm" @submit="handleSearch" @reset="handleReset" />

        <BasicTable
          ref="tableRef"
          :columns="columns"
          :request="loadData"
          :before-request="beforeRequest"
          :row-key="rowKey"
          @checked-row-keys="handleCheckedRowKeys"
          @single-click="handleSingleClick"
          :scroll-x="2500"
        />
      </n-card>
    </template>

    <template #resize-trigger>
      <div class="spliter" title="双击隐藏组织机构" @dblclick.prevent="toggleOrgTree"></div>
    </template>
  </Split>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Split } from '@/components/Split';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import { getMessageLogList } from '@/api/business/showManager/message';

  // 定义响应式数据
  const splitSize = ref(0.23);
  const selectedOrgId = ref('');
  const tableRef = ref();
  const orgTreeRef = ref();
  const checkedRowKeys = ref([]);
  const selectedRow = ref();

  // 表格列配置
  const columns = [
    {
      type: 'selection',
      disabled(row: any) {
        return row.name === 'disabled';
      },
    } as any,
    {
      title: '序号',
      key: 'id',
      width: 20,
      align: 'center',
      className: '',
      render(row, index) {
        return `${index + 1}`;
      },
    },
    {
      title: '消息帧',
      key: 'msgId',
      width: 50,
      align: 'center',
      resizable: true,
    },
    {
      title: '消息栏目',
      key: 'mqttTopic',
      width: 80,
      align: 'left',
    },
    {
      title: '消息负载',
      key: 'payload',
      width: 160,
      align: 'left',
      resizable: true,
    },
    {
      title: '接收时间',
      key: 'receiveTime',
      width: 50,
      align: 'center',
      resizable: true,
    },
    {
      title: '处理时间',
      key: 'handlingTime',
      width: 50,
      align: 'center',
      resizable: true,
    },
    {
      title: '备注',
      key: 'remark',
      width: 100,
      align: 'left',
      resizable: true,
    },
  ];

  // 搜索表单配置
  const searchSchemas = [
    {
      field: 'shoeCode',
      component: 'NInput',
      label: '铁鞋编码',
      giProps: {
        span: 1,
      },
      componentProps: {
        onInput: () => {
          reloadTable();
        },
      },
    },
    {
      field: 'prodCode',
      component: 'NInput',
      label: '出厂编码',
      giProps: {
        span: 1,
      },
      componentProps: {
        onInput: () => {
          reloadTable();
        },
      },
    },
    {
      field: 'receiveTime',
      component: 'NDatePicker',
      label: '接收时间',
      giProps: {
        span: 1,
      },
      componentProps: {
        type: 'date',
        format: 'yyyy-MM-dd',
        valueFormat: 'yyyy-MM-dd',
        onUpdateValue: () => {
          reloadTable();
        },
      },
    },
  ];

  // 注册表单
  const [registerForm, { getFieldsValue }] = useForm({
    gridProps: {
      cols: '4',
    },
    labelWidth: 80,
    showAdvancedButton: false,
    schemas: searchSchemas,
  });

  // 表格行的唯一标识
  const rowKey = (row) => row.infoId;

  // 处理隐藏组织机构树
  function handleHideOrgTree() {
    splitSize.value = 0;
  }

  // 设置选中的组织机构
  function handleSetOrg(orgId, orgName) {
    selectedOrgId.value = orgId;
  }

  // 切换组织机构树显示/隐藏
  function toggleOrgTree() {
    if (splitSize.value > 0) {
      splitSize.value = 0;
    } else {
      splitSize.value = 0.23;
    }
  }

  // 处理组织机构树加载完成事件
  function handleOrgTreeLoaded() {
    // 获取组织树的根节点数量
    const orgTreeComponent = orgTreeRef.value;
    if (orgTreeComponent) {
      // 获取所有节点
      const allNodes = orgTreeComponent.toArray();
      
      // 如果节点数量小于等于1，默认隐藏树结构
      if (allNodes && allNodes.length <= 1) {
        splitSize.value = 0;
      } else {
        // 否则保持默认大小
        splitSize.value = 0.23;
      }
    }
  }

  // 请求前处理参数
  function beforeRequest(params) {
    return Object.assign(params, {
      orgId: selectedOrgId.value,
    });
  }

  // 加载数据
  async function loadData(params) {
    if (!selectedOrgId.value) {
      return {
        list: [],
        itemCount: 0,
      };
    }

    try {
      const searchParams = { ...getFieldsValue(), ...params };
      const result = await getMessageLogList(searchParams);

      return {
        list: result.records || [],
        itemCount: result.total || 0,
      };
    } catch (error) {
      console.error('加载数据失败:', error);
      return {
        list: [],
        itemCount: 0,
      };
    }
  }

  // 处理搜索
  function handleSearch() {
    reloadTable();
  }

  // 处理重置
  function handleReset() {
    reloadTable();
  }

  // 处理选中行
  function handleCheckedRowKeys(keys) {
    checkedRowKeys.value = keys;
  }

  // 处理单击行
  function handleSingleClick(row) {
    selectedRow.value = row;
  }

  // 重新加载表格
  function reloadTable() {
    tableRef.value?.reload();
  }
</script>

<style scoped>
  .proCard {
    width: 100%;
    height: 100%;
  }

  .spliter {
    cursor: col-resize;
    background-color: #e5e7eb;
    height: 100%;
    width: 5px;
  }

  .spliter:hover {
    background-color: #9ca3af;
  }
</style>